package leetcode.median;

/**
 * ClassName: Trie
 * Description:
 * date: 2022-02-19 22:20
 *
 * @author liyifan
 */
public class Trie {
    class TireNode {
        private boolean isEnd;
        TireNode[] next;

        public TireNode() {
            isEnd = false;
            next = new TireNode[26];
        }
    }

    private TireNode root;

    public Trie() {
        this.root =  new TireNode();
    }

    public void insert(String word) {
        TireNode p = this.root;
        for (Character c:word.toCharArray()) {
            if (p.next[c - 'a'] == null) {
                p.next[c - 'a'] = new TireNode();
            }
            p = p.next[c - 'a'];
        }
        p.isEnd = true;
    }

    public boolean search(String word) {
        TireNode p = this.root;
        for (Character c : word.toCharArray()) {
            p = p.next[c - 'a'];
            if (p == null) {return false;}
        }
        return p.isEnd;
    }

    public boolean startsWith(String prefix) {
        TireNode p = this.root;
        for (Character c : prefix.toCharArray()) {
            p = p.next[c - 'a'];
            if (p == null) {return false;}
        }
        return true;
    }
}
